package com.effectiv.crm.service.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;

import jodd.cache.Cache;
import jodd.cache.LRUCache;
import jodd.util.StringUtil;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import com.effectiv.crm.domain.PickListEntry;
import com.effectiv.crm.repository.PickListEntryRepository;
import com.effectiv.crm.service.api.PickListService;

@Named
@Slf4j
public class PickListEntryServiceImpl implements PickListService {
	
	@Inject
	private PickListEntryRepository repository;
	
	@Inject
	private ResourceLoader loader;
	
	//TODO replace with Spring caching
	private Cache<String, List<PickListEntry>> cache = new LRUCache<>(100, 500000);
	
	@Override
	public List<PickListEntry> findByDomain(String domain) {
		
		List<PickListEntry> entries = cache.get(domain);
		
		if(entries == null){
			entries = repository.findByDomain(domain);
			cache.put(domain, entries);
		}	
		return entries; 
	}

	@Override
	public List<PickListEntry> findByKeyAndDomain(String key, String domain) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void save(PickListEntry entry) {
		repository.save(entry);

	}
	
	@PostConstruct
	public void init(){
		
		long totalNoOfEntries = repository.count();
		
		if(totalNoOfEntries == 0){
			Resource resource = loader.getResource("classpath:pick-list.csv");
			log.info("##### Resource = {}", resource);
			
			try (BufferedReader br = new BufferedReader(new InputStreamReader(
					resource.getInputStream(), "UTF-8"))) {
				
				//skip header
				String line = br.readLine();
				String items [] = null;
				List<PickListEntry> entries = new ArrayList<PickListEntry>();
				while ((line = br.readLine()) != null) {
					log.info(line);
					
					if(StringUtil.isNotEmpty(line)){
						items = StringUtil.split(line, ","); 
						PickListEntry e = BeanUtils.instantiate(PickListEntry.class);
						e.setKey(items[0]);
						e.setValue(items[1]);
						e.setDomain(items[2]);
						e.setDescription("Created at application startup by system");
						entries.add(e);
					}
					
				}
				repository.save(entries);
				

			} catch (Exception e) {
				log.error("Error", e);
			}
		}
		
	}

}
